import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;


class NotifyPendingService {

    boolean transactional = false

    def notifyPending( ) {
        def port
        def cv = ClaveValor.findByClave('puerto').each{
            port = Integer.parseInt(it.valor)
        }

        def criteria = DetalleAlimento.createCriteria()
        def results = criteria.list{
            and{
                le("avisos",3)
                eq("iniciado",false)
            }            
        }.each{
            notifyItem(it,port)
        }
    }


    def notifyItem( detalleAlimento, port ){
        def pez = detalleAlimento.pez
        println "enviando ${detalleAlimento.alimento.uuid} a ${pez.nombre}"
        try{
            byte[]buf = detalleAlimento.alimento.uuid.getBytes()
            InetAddress host = InetAddress.getByName(pez.ip)
            DatagramPacket packet = new DatagramPacket(buf,buf.length,host,port)
            DatagramSocket udp = new DatagramSocket()
            udp.send(packet)
        }catch( Exception e){
            log.error(e)
        }
        DetalleAlimento.withTransaction{
            detalleAlimento.avisos++
            detalleAlimento.ultimoAviso = new Date()
            detalleAlimento.save()
        }
    }

}
